#include "../../include/dir.h"

static int rmdir_recursive(const char *dirPath, char *buf, int buf_len){
    DIR *dirp = opendir(dirPath);
    if(!dirp){
        //文件打开失败
        sprintf(buf, "%s\n", strerror(errno));
        return -1;
    }
    
    struct dirent *entry;
    while((entry = readdir(dirp)) != NULL){
        //检查目录中的各类型 做对应删除
        
        //忽略 . ..
        if(strcmp(entry->d_name, ".") == 0||strcmp(entry->d_name, "..") == 0){
            continue;
        }
        
        //将读到名拼接做类型检查->对应删除
        char fullPath[MAX_PATH_LEN] = {0};
        sprintf(fullPath, "%s/%s", dirPath, entry->d_name);

        struct stat st;
        stat(fullPath, &st);
        if(S_ISDIR(st.st_mode)){
           //是目录
           rmdir_recursive(fullPath, buf, buf_len);
        }
        else{
            //不是目录直接unlink删
            if(unlink(fullPath) != 0){
                sprintf(buf, "%s\n", strerror(errno));
                return -1;
            }
        }
    }
    closedir(dirp);

    //递归出口 空目录直接删
    if(rmdir(dirPath) != 0){
        sprintf(buf, "%s\n", strerror(errno));
        return -1;
    }
    
    return 0;
}
    
int handle_rmdir(path_t *path, const char *destDir, char *buf, int buf_len){
    //清空buf 避免调用了多次带buf的函数后面会输出前面buf内容 测试问题mkdir->ls
    bzero(buf, buf_len);
    
    //规范路径
    char newVirPath[MAX_PATH_LEN] = {0};
    char newRealPath[MAX_PATH_LEN] = {0};
    makePath(path, destDir, newVirPath, newRealPath);
    
    //检查文件是否存在
    if(access(newRealPath, F_OK) != 0){
        strncpy(buf, "文件不存在.\n", buf_len-1);
        return -1;
    }

    //检查是否为目录
    struct stat st;
    stat(newRealPath, &st);
    if(!S_ISDIR(st.st_mode)){
        //不是目录
        strncpy(buf, "不是目录.\n", buf_len-1);
        return -1;
    }

    //递归删除目录
    if(rmdir_recursive(newRealPath, buf, buf_len) != 0){
        return -1;
    }
    return 0;
}
